/*
 * Copyright (C) 2011 Johan Kannala
 *
 * Licensed under the MIT License. You can find a copy of the License at in the
 * license.txt file.
 */
package com.joppe.vocabtutor;

import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.*;
import android.os.Bundle;
import android.util.Log;
import android.view.*;
import android.view.animation.*;
import android.view.animation.Animation.AnimationListener;
import android.widget.*;

import com.joppe.vocabtutor.views.*;
import com.joppe.vocabtutor.views.FlipCardAnimation.FlipPhase;

public class WordQuizActivity extends LoggedActivity {
	private VocabTutor mApplication = null;
	private VocabTutorDBHelper mDBHelper = null;
	private Cursor mWordQuizCursor = null;
	private ViewGroup mCards = null;
	private ViewGroup mWordCard = null;
	private ViewGroup mAnswerCard = null;
	private boolean m_wordUpdateNeeded = false;
	private boolean m_answerUpdateNeeded = false;

	/** Called when the activity is first created. */
	@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mApplication = (VocabTutor) this.getApplication();
        mDBHelper = mApplication.getDataHelper();
        setContentView(R.layout.quiz_activity);
        mCards = (ViewGroup) findViewById(R.id.quiz_cards);
        mWordCard = (ViewGroup) findViewById(R.id.quiz_word_card);
        mAnswerCard = (ViewGroup) findViewById(R.id.quiz_answer_card);
        Intent i = getIntent();
        long[] chapterIds = i.getLongArrayExtra("chapter_ids");
        String chaptersString = VocabTutor.toCommaSeparatedString(chapterIds);
        SQLiteDatabase db = mApplication.getDataHelper().getReadableDatabase();
        mWordQuizCursor = db.query("words",
                new String[] { "_id", "word", "times_asked", "correct_answers" },
                "chapter_fk in " + chaptersString, null, null, null, null);
    }
	
	@Override
	public void onResume() {
	    super.onResume();
	    mWordQuizCursor.requery();
	    updateHeader();
	    if (mWordQuizCursor.moveToFirst()) {
	        m_wordUpdateNeeded = true;
	        m_answerUpdateNeeded = true;
	        updateWordCard();
	        updateAnswerCard();
	    }
	}
	
	@Override
    public void onStop() {
        super.onStop();
        mWordQuizCursor.deactivate();
    }
    
    @Override
    public void onDestroy() {
        super.onDestroy();
        mWordQuizCursor.close();
        mWordQuizCursor = null;
    }
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
	    // TODO Nothing to do yet.
		return super.onCreateOptionsMenu(menu);
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
	    // TODO Nothing to do yet.
		return super.onOptionsItemSelected(item);
	}
	
	private void updateHeader() {
	    TextView noWordsLbl = (TextView) findViewById(R.id.quiz_no_words_lbl);
	    TextView correctLbl = (TextView) findViewById(R.id.quiz_correctness_lbl);
	    int wordCnt = mWordQuizCursor.getCount();
        noWordsLbl.setText(Integer.toString(wordCnt));
        if (wordCnt > 0)
            correctLbl.setText("78%");
        else
            correctLbl.setText("xxx");
	}
	
    private void updateWordCard() {
        if (!m_wordUpdateNeeded)
            return;
        Cursor lWordQuizCursor = mWordQuizCursor;
        ViewGroup lWordCard = mWordCard;
        TextView origWordLbl = (TextView) lWordCard.findViewById(R.id.quiz_orig_word_lbl);
        EditText translationFld = (EditText) lWordCard.findViewById(R.id.quiz_translation_fld);
        TextView timesAskedLbl = (TextView) lWordCard.findViewById(R.id.quiz_times_asked_lbl);
        TextView correctAnswersLbl = (TextView) lWordCard.findViewById(R.id.quiz_correct_answers_lbl);
        origWordLbl.setText(lWordQuizCursor.getString(1));
        translationFld.setText("");
        timesAskedLbl.setText(lWordQuizCursor.getString(2));
        correctAnswersLbl.setText(lWordQuizCursor.getString(3));
        m_wordUpdateNeeded = false;
    }
	
    private void updateAnswerCard() {
        if (!m_answerUpdateNeeded)
            return;
        ViewGroup l_answerCard = mAnswerCard;
        Cursor lWordQuizCursor = mWordQuizCursor;
        ViewGroup lTranslationGroup = (ViewGroup) l_answerCard.findViewById(R.id.quiz_translation_group);
        TextView origWordLbl = (TextView) l_answerCard.findViewById(R.id.quiz_orig_word_lbl);
        origWordLbl.setText(lWordQuizCursor.getString(1));
        Cursor transCursor = null;
        try {
            SQLiteDatabase db = mDBHelper.getReadableDatabase();
            transCursor = db.query("translations",
                            new String[] { "_id", "translation" }, "word_fk = ?",
                            new String[] { Integer.toString(lWordQuizCursor.getInt(0)) },
                            null, null, null);
            lTranslationGroup.removeAllViews();
            LayoutInflater li = LayoutInflater.from(this);
            while (transCursor.moveToNext()) {
                TextView transLbl = (TextView) li.inflate(R.layout.quiz_translation_item, null);
                transLbl.setText(transCursor.getString(1));
                lTranslationGroup.addView(transLbl);
            }
        }
        finally {
            if (transCursor != null)
                transCursor.close();
        }
        m_answerUpdateNeeded = false;
    }
    
    private void checkAnswer(String answer) {
        Cursor transCursor = null;
        try {
            int l_wordFk = mWordQuizCursor.getInt(0);
            String queryString = SQLiteQueryBuilder.buildQueryString(false, "translations",
                    new String[] {"translation"}, "word_fk = " + l_wordFk + 
                    " and translation = '" + answer + "'",
                    null, null, null, null);
            SQLiteDatabase db = mDBHelper.getReadableDatabase();
            transCursor = db.rawQuery(queryString, null);
            Log.d("com.joppe.vocabtutor", queryString);
            while (transCursor.moveToNext())
                Log.i("com.joppe.vocabtutor", transCursor.getString(0));
            TextView corrIncorrLbl = (TextView) findViewById(R.id.quiz_correct_incorrect_lbl);
            if (transCursor.getCount() > 0) {
                Log.d("com.joppe.vocabtutor", "Correct answer");
                corrIncorrLbl.setText(R.string.quiz_correct_string);
                corrIncorrLbl.setTextColor(getResources().getColor(R.color.quiz_correct_color));
            }
            else {
                Log.d("com.joppe.vocabtutor", "Incorrect answer");
                corrIncorrLbl.setText(R.string.quiz_incorrect_string);
                corrIncorrLbl.setTextColor(getResources().getColor(R.color.quiz_incorrect_color));
            }
        }
        finally {
            if (transCursor != null)
                transCursor.close();
        }
    }
	
	public void checkAnswerClicked(View button) {
	    FlipCardAnimation anim = new FlipCardAnimation(400, FlipPhase.HideWord);
	    anim.setAnimationListener(new AnimationListener() {
            @Override
            public void onAnimationStart(Animation animation) {
            }
            @Override
            public void onAnimationRepeat(Animation animation) {
            }
            @Override
            public void onAnimationEnd(Animation animation) {
                mCards.post(new CardSwitcher(FlipPhase.HideWord));
            }
        });
	    EditText answerFld = (EditText) findViewById(R.id.quiz_translation_fld);
	    checkAnswer(answerFld.getText().toString());
	    mCards.startAnimation(anim);
	}
	
	public void nextWordClicked(View view) {
	    FlipCardAnimation anim = new FlipCardAnimation(400, FlipPhase.HideAnswer);
	       anim.setAnimationListener(new AnimationListener() {
	            @Override
	            public void onAnimationStart(Animation animation) {
	                mCards.post(new Runnable() {
	                    @Override
	                    public void run() {
	                        updateWordCard();
	                    }
	                });
	            }
	            @Override
	            public void onAnimationRepeat(Animation animation) {}
	            @Override
	            public void onAnimationEnd(Animation animation) {
	                mCards.post(new CardSwitcher(FlipPhase.HideAnswer));
	            }
	        });
        mCards.startAnimation(anim);
        if (mWordQuizCursor.moveToNext()) {
            m_wordUpdateNeeded = true;
            m_answerUpdateNeeded = true;
        }
	}
	
	class CardSwitcher implements Runnable {
	    private FlipPhase phase;
	    CardSwitcher(FlipPhase currentPhase) {
	        this.phase = currentPhase;
	    }
	    public void run() {
	        switch(phase) {
            case HideWord:
                mWordCard.setVisibility(View.GONE);
                mAnswerCard.setVisibility(View.VISIBLE);
                FlipCardAnimation anim = new FlipCardAnimation(400, FlipPhase.ShowAnswer);
                mCards.startAnimation(anim);
                break;
            case ShowAnswer:
                // End state. Do nothing?
                break;
            case HideAnswer:
                mWordCard.setVisibility(View.VISIBLE);
                mAnswerCard.setVisibility(View.GONE);
                anim = new FlipCardAnimation(400, FlipPhase.ShowWord);
                mCards.startAnimation(anim);
                updateAnswerCard();
                break;
            case ShowWord:
                // End state. Do nothing?
                break;
            }
	    }
	}
}